package com.scorpio.appuser.service.impl;

import java.util.Arrays;
import java.util.List;

import com.scorpio.appuser.service.UserInvoiceService;
import com.scorpio.common.exception.CustomException;
import com.scorpio.redis.cachelock.RedisLock;
import com.scorpio.redis.cachelock.RedisLockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.scorpio.appuser.mapper.UserInvoiceMapper;
import com.scorpio.appuser.domain.UserInvoiceEntity;
import com.scorpio.common.service.impl.BaseServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 发票信息Service业务层处理
 *
 * @author scorpio
 * @date 2022-01-05
 */
@Service
public class UserInvoiceServiceImpl extends BaseServiceImpl<UserInvoiceMapper, UserInvoiceEntity> implements UserInvoiceService {

    @Autowired
    private RedisLock redisLock;

    @Override
    public UserInvoiceEntity selectById(Long id) {
        return baseDao.selectById(id);
    }

    @Override
    public UserInvoiceEntity selectByUser(Long uid) {
        return baseDao.selectByUser(uid);
    }

    @Override
    public UserInvoiceEntity save(UserInvoiceEntity entity) {
        if (entity.getUid() == null) {
            throw new CustomException("无效操作");
        }
        String lockKey = "UserInvoiceServiceImpl_save:" + entity.getUid();
        if (redisLock.lock(lockKey, 5)) {
            try {
                UserInvoiceEntity old = baseDao.selectByUser(entity.getUid());
                if (old != null) {
                    old.setName(entity.getName());
                    old.setCreditCode(entity.getCreditCode());
                    old.setMailbox(entity.getMailbox());
                    if (baseDao.updateById(old) == 0) {
                        throw new CustomException("操作失败");
                    }
                    return old;
                } else {
                    if (baseDao.insert(entity) == 0) {
                        throw new CustomException("操作失败");
                    }
                    return entity;
                }
            } finally {
                redisLock.unlock(lockKey);
            }
        }
        throw new RedisLockException();
    }
}
